package com.jeeinc.oa.utils;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JsonBinder {
	private final static Logger logger = LoggerFactory.getLogger(JsonBinder.class);
	private final static ObjectMapper mapper = new ObjectMapper();

	static {
		mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
	}

	/**
	 * 将对象转换成json字符串
	 * 
	 * @param object
	 *            欲转换的对象
	 * @return
	 */
	public static String toJson(Object object) {
		try {
			return mapper.writeValueAsString(object);
		} catch (IOException e) {
			logger.warn("write to json string error:" + object, e);
			return null;
		}
	}

	/**
	 * json转指定对象
	 * @param json
	 * @param valueType
	 * @return
	 */
	public static <T> T toEntity(String json, Class<T> valueType) {
		if (json == null || json.trim().equals("")) return null;
		
		try {  
			return mapper.readValue(json, valueType);  
		} catch (IOException e) {
			logger.warn("json write to entity string error:" + json, e);
		}  
		return null; 
	}

}
